<template>

  <a-modal :open="open" :title="title" @ok="handleOk" @cancel="cancel" okText="确定" cancelText="取消">
    <a-form :model="roleForm" v-bind="layout" ref="roleFormRef">
      <a-form-item label="角色名称" name="name">
        <a-input v-model:value="roleForm.name" />
      </a-form-item>
      <a-form-item label="角色码"  name="code">
        <a-input v-model:value="roleForm.code" />
      </a-form-item>
     
      <a-form-item label="角色描述" name="description">
        <a-input v-model:value="roleForm.description" />
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script setup name="RoleModal">
import { addRole,updateRole } from '@/api/role';
import { ref } from 'vue';
import { message } from 'ant-design-vue';
//定义弹框关闭 页面要刷新
const emit = defineEmits(['refresh'])
const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 16,
  },
};
//弹框的开关
const open = ref(false)
//标题
const title=ref('新增')
//表单对象
const roleForm = reactive(
  {
    id:'',
    name: '',
    code: '',
    description: ''

  }
);
//表单对象 用于清空表单数据
const roleFormRef = ref();
//弹框类型 默认是新增
const type=ref(true)

//设置弹框的开闭 第一个参数是否是是新增  第二个参数是数据
function openModal(isNew=true,data) {
  open.value = true;
  if(!isNew && data){
    title.value = '编辑';
    type.value=false;
    for(const key in roleForm){
      roleForm[key]=data[key]
    }
  }else{
    type.value=true;
    title.value = '新建'
  }
}
//关闭弹框
const cancel = e => {
  open.value = false
  roleFormRef.value.resetFields();
}
//提交
const handleOk = async e => {
  if(type.value){
    const rs = await addRole(roleForm)
  }else{
    const rs = await updateRole(roleForm)
    
  }
  message.success({
    content:"成功",
    duration:1,
    onClose:()=>{
      roleFormRef.value.resetFields();
  open.value= false;
  emit('refresh')
    }
  }) 
 

  
};
//在这里暴露这个方法 在外面调用
defineExpose({ openModal })

</script>

<style scoped>
.ant-form {
  margin-top: 36px;
}
</style>